const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");
router.post('/scan/findReceiptById', async ctx => {
    let body = ctx.request.body
    let user = ctx.user
    let tenantId = user.tenantId;
    /**
     * 扫码找单据
     */
    try {
        let scanInfo = body.scanInfo;
        if (!scanInfo) {
            return ctx.err('未找到数据');
        }
        let ret = scanInfo.split('-');
        let transType = tool.xe.toNumber(ret[0])
        let billId = tool.xe.toNumber(ret[1])
        // 出入库票据
        if ([150601, 150602, 150603].indexOf(transType) !== -1) {
            let sqlStr = ` select a.id,billType,transTypeName,totalAmount,buId,billDate,billState,accId,accId1,transType,billNo,dbo.setBillState(billState) billStateName,
                       a.arrearsReal-a.hxAmount leftAmount,a.amount,arrears,b.name as buName,a.linkName,
                       a.address,a.salesId,c.name as salesName,a.deliverNames,deliverNames,a.linkMobile,a.remark
                from v_main_withhx a left join contact b on a.buId=b.id left join admin c on a.salesId=c.id
                where a.tenantId=${tenantId} and a.id=${billId}
            `
            let invoice = await db.query(sqlStr, {type: QueryTypes.SELECT, plain: true})
            let transType = tool.xe.toNumber(invoice.transType)
            if (!invoice) return ctx.err('未找到该票据');
            if (invoice.billState !== 'draft') {
                if (tool.xe.toNumber(invoice.leftAmount) === 0) {
                    return ctx.err('该票据应收金额为 0 ');
                }
            }

            if (transType === 150502 || transType === 150602) {
                invoice.leftAmount = -invoice.leftAmount
                invoice.hxAmount = -invoice.hxAmount
            }
            // 是否已审核，是就返回审核凭证     // 凭证号
            let cardNo = await db.models['card'].findOne({
                where: {
                    tenantId,
                    byIid: billId,
                },
                attributes: ['billNo']
            })
            let sfkNo = await db.query(`select b.* from invoice a inner join invoice_receipt b on a.id=b.iid 
                                        and a.tenantId=${tenantId} and b.billId=${billId} and a.billState='accounted'`, {type: QueryTypes.SELECT})
            invoice.cardNo = cardNo?cardNo.billNo: '';
            let sfk = []
            sfkNo.map(item => {
                sfk.push(item.billNo)
            })
            invoice.sfkNo = sfk;
            if (invoice.billState === 'draft') {
                invoice.state = '草稿';
            }
            if (invoice.billState === 'accounted') {
                invoice.state = '已审核';
            }
            if (invoice.billState === 'del') {
                invoice.state = '已删除';
            }
            if (tool.xe.toNumber(invoice.leftAmount) === 0) {
                invoice.payState = '已核销';
            }
            if (tool.xe.toNumber(invoice.leftAmount) !== 0) {
                invoice.payState = '部分核销';
            }
            if (tool.xe.toNumber(invoice.hxAmount) === 0) {
                invoice.payState = '未核销';
            }
            // 仓库
            let location = await db.models['invoiceInfo'].findOne({
                where: {
                    iid: billId
                }
            })
            let locationId = location.locationId;
            let locationName = location.locationName;
            let sql = `select a.price,b.id as invId,b.name invName,b.spec,b.unit1 unit,b.unit1,b.unit2,'' qty, ${locationId} as locationId,'${locationName}' as locationName,'' amount 
                                from goods_back a inner join v_goods b on a.invId=b.id and a.tenantId=${tenantId}`;
            invoice.goods = await db.query(sql, {type: QueryTypes.SELECT}) // 关联退货
            let dikouSql = `
                select a.id,b.name as buName,billNo,arrears,transTypeName,c.name as salesName,a.buId,deliverNames,totalAmount,transTypeName,leftAmount,billDate,billType,transType,hxAmount,a.billState,dbo.setBillState(bilLState) billStateName from 
                invoice a left join contact b on a.buId=b.id left join admin c on a.salesId=c.id 
                where a.tenantId=${tenantId} and transType in(150602, 153405) and billState in('accounted', 'draft') and isnull(leftAmount,0) <> 0 and a.buId=${invoice.buId}
            `
            invoice.dikouList = await db.query(dikouSql, {type: QueryTypes});
            invoice.accountId = 0;
            invoice.accountName = '';
            invoice.leftAmount = tool.xe.subtract(invoice.arrears, invoice.hxAmount)

            // 上次收款用的账户
            if (invoice.buId) {
                let acc = `SELECT accId from invoice where tenantId=1 and buId=${invoice.buId} and billType='RECEIPT' and buId<>0 ORDER BY id desc`;
                let accA = await db.query(acc, {type: QueryTypes.SELECT, plain: true})
                let accId = 0;
                if (accA) {
                    accId = accA.accId;
                }
                if (accId) {
                    let account = await db.models['category'].findOne({
                        where: {
                            tenantId,
                            id: accId
                        },
                        attributes: ['id', 'name']
                    })
                    invoice.accountName = account.name;
                    invoice.accountId = accId;
                }
            }
            return ctx.suc('', invoice);
        }
        else {
            return ctx.err('非销售单据')
        }
    } catch (e) {
        return ctx.err(e);
    }
})


module.exports = router;
